<?php

namespace Modules\Api\Service;

use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\GoodsCateRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\CollectRepository;
use HiCommon\MongodbModel\MongoSearchGoods;
use HiCommon\Repository\GoodsSaleTagRepository;

class GoodsService extends BaseService
{
    /**
     *  分类商品列表
     *
     *  2019 11 25
     **/
    public function get_cate_goods_list($arrInput)
    {
        try {
            $type = intval($arrInput['type']);
            $temp = [];
            if ($type == 1) { //普通商品
                $type_map = ['pid' => 0, 'status' => 1, 'type' => 1];
                $goods_map = ['status' => 1, 'type' => $type/*, 'repairstore_id' => 1*/];
            } elseif ($type == 2) {//积分商品
                $type_map = ['pid' => 0, 'status' => 1, 'type' => 2];
                $goods_map = ['status' => 1, 'type' => $type];
                //获取当前用户的可用积分
                $arr_where['field'] = ['id', 'integral'];
                $arr_user_info = UsersRepository::get_one((int)api_user_id(), (array)$arr_where);
                if ($arr_user_info->first()) {
                    $temp['user'] = $arr_user_info->toArray();
                }
            } else {
                return hello_error('类型错误');
            }
            //获取商品分类
            $arr_type = GoodsCateRepository::get_cate_list($type_map);

            $field = ['id', 'pic_url', 'title', 'name'];
            $goods = [];
            foreach ($arr_type as $key => $value) {
                $goods_map['cate_id'] = $value['id'];
                $goods_info = GoodsRepository::get_list_where_limit((array)$goods_map, 3, $field)->toarray();
                $goods_list = self::goods_list_data_handle($goods_info);
                if ($goods_list) {
                    $goods[$key]['type'] = $value['id'];
                    $goods[$key]['title'] = $value['name'];
                    $goods[$key]['goods'] = $goods_list;
                }
            }

            $temp['goods_list'] = array_values($goods);

            return hello_success('获取成功', $temp);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 筛选条件
     * @param array $arrInput
     * @return mixed
     */
    public function where_search(array $arrInput)
    {
        $shop_id = intval($arrInput['shop_id']);//门店id
        $type = intval($arrInput['type']);//商品类型
        $cate_id = intval($arrInput['cate_id']);//商品分类
        $sell = intval($arrInput['sell']);
        $price = intval($arrInput['price']);
        $is_free = intval($arrInput['is_free']);
        $min_price = intval($arrInput['min_price']);
        $max_price = intval($arrInput['max_price']);
        $sale_tag = intval($arrInput['sale_tag']);
        $stock = intval($arrInput['stock']);

        $arr_where['where']['status'] = 1;

        if ($shop_id) {
            $arr_where['where']['repairstore_id'] = $shop_id;
        }
        if ($type) {
            $arr_where['where']['type'] = $type;
        }

        //是否包邮
        if ($is_free == 1) {
            $arr_where['where']['is_free'] = 1;
        }

        if ($cate_id > 0) {
            $arr_where['where']['cate_id'] = $cate_id;
        }

        //销量排序
        if ($sell == 1) {
            $arr_where['order'] = ['key' => 'sell', 'value' => 'desc'];
        }
        if ($sell == 2) {
            $arr_where['order'] = ['key' => 'sell', 'value' => 'asc'];
        }

        //价格排序
        if ($price == 1) {
            $arr_where['order'] = ['key' => 'min_price', 'value' => 'desc'];
        }
        if ($price == 2) {
            $arr_where['order'] = ['key' => 'min_price', 'value' => 'asc'];
        }

        //价格区间
        if ($min_price) {
            $arr_where['map']['min_price'] = $min_price;
        }
        if ($max_price) {
            $arr_where['map']['max_price'] = $max_price;
        }

        //服务标签
        if ($sale_tag) {
            $arr_where['map']['sale_tag'] = $sale_tag;
        }

        //是否有库存
        if ($stock) {
            $arr_where['map']['stock'] = $stock;
        }

        return $arr_where;
    }

    /**
     * 指定-类型-分类商品列表
     *
     * 2019 11 25
     **/
    public function get_cate_goods_more(array $arrInput)
    {
        try {
            $type = intval($arrInput['type']);//商品类型
            if (!in_array($type, [1, 2])) {
                return hello_error('商品类型错误');
            }

            $arr_where = self::where_search($arrInput);

            $arr_where['field'] = ['id', 'name', 'title', 'pic_url', 'price', 'integral', 'sell', 'repairstore_id'];
            $arr_where['with'] = ['product_info'];

            $goods_obj = GoodsRepository::search_goods_list((array)$arr_where);
            $goods_array = list_page_data($goods_obj);

            $res['goods_list'] = self::goods_list_data_handle($goods_array['data']);
            $res['page'] = $goods_array['page_data'];

            return hello_success('获取成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *  获取商品详情
     *
     *  2019 11 25
     **/
    public function get_goods_info(int $nId)
    {
        try {
            if (empty($nId)) {
                return hello_error('商品id不能为空');
            }
            //获取商品的主表信息
            $arr_option['with'] = ['img', 'shop_name', 'sale_tag_relation' => function ($query) {
                $query->with(['sale_tag']);
            }];
            $goods_obj = GoodsRepository::get_one((int)$nId, (array)$arr_option);
            if ($goods_obj->first()) {
                if($goods_obj->status == 2){
                    return hello_error('该商品已下架！');
                }

                $result = self::goods_data_handle($goods_obj);//商品基础信息

                $result['is_collect'] = false; //未收藏
                $user_id = api_user_id();
                if (!empty($user_id)) {
                    $arr_where = ['x_id' => $nId, 'user_id' => $user_id, 'type' => 1];
                    $count = CollectRepository::get_count_by_where((array)$arr_where);
                    if ($count > 0) {
                        $result['is_collect'] = true;//收藏
                    }
                }
                $coupon_data = ['shop_id' => $goods_obj->repairstore_id, 'type' => 1];
                $arr_list = CouponService::my_coupon_to_shop($coupon_data);
                $result['coupon'] = $arr_list['data'];
                $result['shop'] = $goods_obj->shop_name;

                $result['sale_tag'] = array_column($goods_obj->sale_tag_relation->toArray(), 'sale_tag');

                return hello_success('获取成功', $result);
            }

            return hello_error('商品不存在');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 商品详情数据处理
     *
     */
    public function goods_data_handle($goods_obj)
    {
        $goods = $goods_obj->toArray();
        $http = env('API_HOST', 'https://xdminiapi.chxing.cn');

        if (stripos($goods['detail'], '<img src="/')) {
            $goods['detail'] = str_replace('src="/', 'src="' . $http . '/', $goods['detail']);
            $goods['detail'] = str_replace('/>', ' align="center" width="100%"/>', $goods['detail']);
        }
        $img_array = [];
        if ($goods['img']) {
            foreach ($goods['img'] as $key => $value) {
                $img_array[] = $value['picurl']['full_src'];
            }
        }
        $product = self::get_goods_product((int)$goods['id']);//商品规格信息

        $info = [
            'shop_id' => $goods['repairstore_id'],
            'goods_id' => $goods['id'],
            'goods_name' => $goods['name'],
            'goods_title' => $goods['title'],
            'goods_price' => $goods['price'],
            'goods_detail' => $goods['detail'],
            'price_indication' => $goods['price_indication'],
            'goods_sale' => $goods['sale'],
            'goods_price_region' => $product['data']['goods_price_region'],
            'goods_integral_region' => $product['data']['goods_integral_region'],
            'goods_sell' => $goods['sell'],
            'goods_img' => $img_array,
        ];

        return ['goods' => $info, 'product' => $product['data']];
    }

    /**
     * 获取商品规格属性
     */
    public function get_goods_product(int $nId)
    {
        try {
            if (empty($nId)) {
                return hello_error('商品id错误');
            }
            $where = ['goods_id' => $nId];
            $res = GoodsProductRepository::get_list_where($where);
            $info = [];
            $price = [];
            $integral = [];
            $stock_total = 0;
            foreach ($res as $key => $item) {
                $price[] = $item['price'];
                $integral[] = $item['integral'];
                $stock_total += $item['stock'];
                $info['specsCate'] = $item['specs']['specs_cate']['name'];
                $info['specs'][] = [
                    'product_id' => $item['id'],
                    'product_name' => $item['specs']['name'],
                    'integral' => $item['integral'],
                    'price' => $item['price'],
                    'stock' => $item['stock'],
                    'pic' => $item['pic']['full_src'],
                ];
            }
            $info['stock_total'] = $stock_total;//总库存

            $min_price = number_format_money(min($price));
            $max_price = number_format_money(max($price));
            $info['goods_price_region'] = $min_price == $max_price ? $min_price : $min_price . '-' . $max_price;

            $min_integral = min($integral);
            $max_integral = max($integral);
            $info['goods_integral_region'] = $min_integral == $max_integral ? $min_integral : $min_integral . '-' . $max_integral;

            if ($info) {
                return hello_success('获取成功', $info);
            }

            return hello_error('暂无数据');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 个人中心推荐商品列表
     *
     * 2019 12 25
     **/
    public function recommend_goods_list()
    {
        try {
            $arr_where['where'] = ['status' => 1, 'is_recommend' => 1, 'type' => 1];
            $arr_where['field'] = ['id', 'name', 'title', 'pic_url', 'price', 'integral', 'sell'];
            $arr_where['n_per_page'] = 10;
            $arr_where['with'] = ['product_info'];
            $goods_obj = GoodsRepository::get_list((array)$arr_where);
            $goods_array = list_page_data($goods_obj);

            $res['goods_list'] = self::goods_list_data_handle($goods_array['data']);
            $res['page'] = $goods_array['page_data'];

            return hello_success('获取成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *  商品搜索联想
     *
     * 2020 01 06
     */
    public function suggest_list($arrInput)
    {
        try {
            $arr_where['like'] = $arrInput['key'];
            $arr_where['where'] = ['status' => 1, 'type' => 1];
            $arr_where['field'] = ['name'];

            $goods_obj = GoodsRepository::search_goods_list((array)$arr_where);
            $goods_array = list_page_data($goods_obj);
            $list = [];
            if ($goods_array['data']) {
                $list = array_column($goods_array['data'], 'name');
            }

            return hello_success('获取成功', $list);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *  商品搜索接口
     *
     * 2020 01 02
     */
    public function search_goods_list($arrInput)
    {
        try {
            $arrInput['type'] = 1;
            $arr_where = self::where_search($arrInput);

            $arr_where['like'] = $arrInput['title'];
            $arr_where['field'] = ['id', 'name', 'title', 'pic_url', 'price', 'integral', 'sell'];
            $arr_where['with'] = ['product_info'];

            $goods_obj = GoodsRepository::search_goods_list((array)$arr_where);
            $goods_array = list_page_data($goods_obj);

            $res['goods_list'] = self::goods_list_data_handle($goods_array['data']);
            $res['page'] = $goods_array['page_data'];

            if (!empty($arrInput['title']) && $res['goods_list']) {
                self::add_to_redis($arrInput['title']);
            }

            return hello_success('获取成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 商品列表商品数组处理
     */
    public function goods_list_data_handle($data = [])
    {
        $list = [];
        foreach ($data as $k => $val) {
            $price = array_column($val['product_info'], 'price');
            $integral = array_column($val['product_info'], 'integral');

            $list[$k]['goods_id'] = $val['id'];
            $list[$k]['goods_name'] = $val['name'];
            $list[$k]['goods_title'] = $val['title'];
            $list[$k]['goods_pic'] = $val['pic_url']['full_src'];
            $list[$k]['price'] = number_format_money(min($price) ?? 0.00);
            $list[$k]['integral'] = min($integral) ?? 0;
            $list[$k]['sell'] = $val['sell'];
        }

        return $list;
    }

    /**
     * 把搜索数据存入mongo
     */
    public function add_to_redis($search)
    {
        $arr_data = ['search_title' => $search, 'num' => 1];

        //查询关键词是否存在
        $find = MongoSearchGoods::where('search_title', $search)->first();
        if ($find) {
            $num = $find->num + 1;
            MongoSearchGoods::where('search_title', $search)->update(['num' => $num]);
        } else {
            MongoSearchGoods::create($arr_data);
        }
    }

    /**
     * 获取热门搜索
     */
    public function hot_search_title()
    {
        try {
            $list = MongoSearchGoods::orderBy('num', 'desc')->paginate(10)->toArray();
            $res = array_column($list['data'], 'search_title');

            return hello_success('获取成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *  获取商品搜索标签
     */
    public function search_goods_tag()
    {
        try {
            $cate_option['field'] = ['id', 'name'];
            $cate_option['where'] = ['type' => 1, 'status' => 1];
            $cate_arr = GoodsCateRepository::get_all_list($cate_option)->toArray();

            $tag_option['field'] = ['id', 'name'];
            $tag_option['where'] = ['status' => 1];
            $tag_arr = GoodsSaleTagRepository::get_all($tag_option)->toArray();

            $result = ['cate' => $cate_arr, 'tag' => $tag_arr];

            return hello_success('获取成功', $result);

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

}